package org.pyq.core.process;

import javassist.*;
import org.pyq.core.exception.AgentCoreException;

import java.lang.instrument.Instrumentation;

/**
 * @author pengYongQiang
 * @date 2022/1/7 17:51
 */
public abstract class AbsProcess implements Process {

    private final String className;
    private Instrumentation instrumentation;
    private Class<?> targetClass;
    private ClassLoader targetClassLoader;

    public AbsProcess(String className, Instrumentation instrumentation) {
        this.className = className;
        this.instrumentation = instrumentation;
    }

    @Override
    public String getClassName() {
        return className;
    }

    @Override
    public Class<?> getClazz() {
        return targetClass;
    }

    @Override
    public void init() {
        Class<?>[] allLoadedClasses = instrumentation.getAllLoadedClasses();
        for (Class<?> clazz : allLoadedClasses) {
            if (clazz.getName().equals(className)) {
                targetClass = clazz;
                targetClassLoader = clazz.getClassLoader();
            }
        }

        if (targetClass == null) {
            throw new AgentCoreException("找不到增强的目标类:" + className);
        }
    }

    @Override
    public byte[] reset() {

        return Process.super.reset();
    }
}
